package com.hbpu.encap.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class UDPReciverA {
    public static void main(String[] args) throws SocketException {
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
        try {
            System.out.println("正在等待接收消息.......");
            datagramSocket.receive(datagramPacket);
            System.out.println("接收成功！");
            System.out.print("接收消息为：");
            String message = new String(buffer, 0, datagramPacket.getLength(), StandardCharsets.UTF_8);
            System.out.println(message);

            try {
                System.out.println("回复消息：好的，明天去");
                byte[] bytes = "好的，明天去".getBytes();
                DatagramPacket datagramPacket1 = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9998);
                datagramSocket.send(datagramPacket1);
                System.out.println("消息发送成功！");
            } catch (IOException e) {
                System.out.println("发送失败：" + e.getMessage());
            }

        } catch (IOException e) {
            System.out.println("接收失败：" + e.getMessage());
        } finally {
            datagramSocket.close();
        }
    }
}
